package com.woniu.consume;

import com.rabbitmq.client.Channel;
import com.woniu.entity.Order;
import com.woniu.mapper.OrderMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 15分钟后检查订单状态的消费者
 */
@Component
public class CheckOrderConsume {
    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = "checkOrder")
    public void receive(String msg, Message message, Channel channel){
        try {
            //1：拿到消息
            //2：消费消息
            //根据订单的编号获取订单的状态
            //如果是未付款状态，修改订单状态，修改库存，维护 redis数据
            Order order = orderMapper.queryOrderByOrderNum(msg);
            if("1".equals(order.getStatus()+"")){//未付款
                orderMapper.updateOrderStatus(msg);
            }
            System.out.println("消费者接收到消息："+msg);
            //3：确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                e.printStackTrace();
            }
        }
    }
}
